/*global $, window*/
//editor 作为editableTableWidget的全局变量 
var activetemp;//activetemp 跟input一样要做全局化处理。跟act一样 保存当前表格td焦点。  先测试 后优化
var editor;
//$('#wwf').parent() id为wwf的div 需要手动修改，这样就可以使用多表格，编辑如新增表 删除表，调整表的行。
editor = $('<input  id="test" type="text" list="typelist" placeholder="请选择">').css('position', 'relative').hide().appendTo($('#wwf').parent());
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//与input和activetemp相关 代码全部移出。
var setactivetempText = function() {

	var text = editor.val(), evt = $.Event('change'), originalContent;
	if (activetemp.text() === text || editor.hasClass('error')) {
		return true;
	}

	originalContent = activetemp.html();

	activetemp.text(text).trigger(evt, text);// 把input的值付给当前td，然后调用'change'事件，对td的值进行验证，如果失败，则还原.

	if (evt.result === false) {
		// 在这里验证 验证失败还原保存值
		activetemp.html(originalContent);
	}
};

var ARROW_LEFT = 37, ARROW_UP = 38, ARROW_RIGHT = 39, ARROW_DOWN = 40, ENTER = 13, ESC = 27, TAB = 9;
var movement = function(element, keycode) {
	if (keycode === ARROW_RIGHT) {
		return element.next('td');
	} else if (keycode === ARROW_LEFT) {
		return element.prev('td');
	} else if (keycode === ARROW_UP) {
		return element.parent().prev().children().eq(element.index());
	} else if (keycode === ARROW_DOWN) {
		return element.parent().next().children().eq(element.index());
	}
	return [];
}
var ttmp = 0;
editor.blur(function() {

	setactivetempText();
	editor.hide();
}).keydown(function(e) {
	if (e.which === ENTER) {
		setactivetempText();
		editor.hide();
		activetemp.focus();
		e.preventDefault();
		e.stopPropagation();
	} else if (e.which === ESC) {
		editor.val(activetemp.text());
		e.preventDefault();
		e.stopPropagation();
		editor.hide();
		activetemp.focus();
	} else if (e.which === TAB) {
		activetemp.focus();
	} else if (this.selectionEnd - this.selectionStart === this.value.length) {
		var possibleMove = movement(activetemp, e.which);
		if (possibleMove.length > 0) {
			possibleMove.focus();
			e.preventDefault();
			e.stopPropagation();
		}
	}
}).on('input paste', function() {
	var evt = $.Event('validate');
	activetemp.trigger(evt, editor.val());
	if (evt.result === false) {
		editor.addClass('error');
	} else {
		editor.removeClass('error');
	}
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////    
$.fn.editableTableWidget = function (options) {
	'use strict';
	
	return $(this).each(function () {		
		 
		var //buildDefaultOptions = function () {var opts = $.extend({}, $.fn.editableTableWidget.defaultOptions);opts.editor = opts.editor.clone();	return opts;},
			//activetempOptions = $.extend(buildDefaultOptions(), options),
			//ARROW_LEFT = 37, ARROW_UP = 38, ARROW_RIGHT = 39, ARROW_DOWN = 40, ENTER = 13, ESC = 27, TAB = 9,
			element = $(this),
			//editor = activetempOptions.editor.css('position', 'relative').hide().appendTo(element.parent().parent().parent()),//使用appendTo添加元素到父元素的父元素#wwf的末尾。input使用 相对定位。//https://www.w3school.com.cn/tiy/t.asp?f=jquery_manipulation_appendto         
			showEditor = function (select) {
				
				activetemp = element.find('td:focus');
				
				if (activetemp.length) {
					editor.val(activetemp.text())
						.removeClass('error')
						.show()
						.offset(activetemp.offset())
						//.css(activetemp.css(activetempOptions.cloneProperties))
						.width(activetemp.width()+10)
						.height(activetemp.height()+10)
						.focus();
					if (select) {
						editor.select();
					}
				}
				
				act=activetemp;//给全局变量赋值。
				
			};		
			
		element.on('click keypress dblclick', showEditor)
		.css('cursor', 'pointer')
		.keydown(function (e) {
			var prevent = true,
				possibleMove = movement($(e.target), e.which);
			if (possibleMove.length > 0) {
				possibleMove.focus();
			} else if (e.which === ENTER) {
				showEditor(false);
			} else if (e.which === 17 || e.which === 91 || e.which === 93) {
				showEditor(true);
				prevent = false;
			} else {
				prevent = false;
			}
			if (prevent) {
				e.stopPropagation();
				e.preventDefault();
			}
		});

		element.find('td').prop('tabindex', 1);

		$(window).on('resize', function () {
			if (editor.is(':visible')) {
				editor.offset(activetemp.offset())
				.width(activetemp.width())
				.height(activetemp.height());
			}
		});
	});

};
$.fn.editableTableWidget.defaultOptions = {
	cloneProperties: ['padding', 'padding-top', 'padding-bottom', 'padding-left', 'padding-right',
					  'text-align', 'font', 'font-size', 'font-family', 'font-weight',
					  'border', 'border-top', 'border-bottom', 'border-left', 'border-right'],
	editor: $('<input  id="test" type="text" list="typelist" placeholder="请选择">')
};

